package chapter7classloader;

import java.io.IOException;
import java.io.InputStream;

public class P78 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //自定义的类加载器和虚拟机默认的启动类加载器 加载的类是不相等的，因为判断类相等是根据类的全名以及类加载器名一起决定的
        //自定义的类加载器可以从任何地方加载一个类，也就是加载一个二进制流

        ClassLoader classLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                String fileName = name.substring(name.lastIndexOf(".")+1)+".class";
                InputStream inputStream = getClass().getResourceAsStream(fileName);
                System.out.println(fileName);
                if (inputStream == null){
                    System.out.println("没有这个文件");
                    return super.loadClass(name);
                }else {
                    try {
                        byte[] bytes = new byte[inputStream.available()];
                        inputStream.read(bytes);
                        return defineClass(name,bytes,0,bytes.length);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return super.loadClass(name);
                    }
                }

            }
        };
        Object o = classLoader.loadClass("chapter7classloader.Foo").newInstance();
        System.out.println(o.getClass());
        System.out.println(o instanceof Foo);

        Foo foo = new Foo();
        System.out.println(foo instanceof Foo);

    }
}
